package com.wen.common.interceptor;

import cn.hutool.core.exceptions.ExceptionUtil;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.wen.common.annotation.RepeatSubmit;
import com.wen.common.utils.ResponseResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;

/**
 * 重复提交拦截器
 *
 * @author liwen <devinlive@163.com>
 * @version 1.0
 * @since 2022/12/9 18:07
 */
@Slf4j
public abstract class RepeatSubmitInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        if (handler instanceof HandlerMethod) {
            HandlerMethod handlerMethod = (HandlerMethod) handler;
            Method method = handlerMethod.getMethod();
            RepeatSubmit annotation = method.getAnnotation(RepeatSubmit.class);
            if (annotation != null && this.isRepeatSubmit(request, annotation)) {
                Map<String, Object> map = new HashMap<>();
                map.put("status", 500);
                map.put("msg", annotation.message());
                response.setContentType("application/json;charset=utf-8");
                try (PrintWriter printWriter = response.getWriter()) {
                    printWriter.write(new ObjectMapper().writeValueAsString(ResponseResult.error("10000",annotation.message())));
                } catch (IOException e) {
                    log.info("printWriter: error{}", ExceptionUtil.getMessage(e));
                    return false;
                }
                return false;
            }
        }
        return true;
    }

    /**
     * 验证是否重复提交由子类实现具体防重复提交的规则
     */
    public abstract boolean isRepeatSubmit(HttpServletRequest request, RepeatSubmit annotation);
}